<!-- #layout name=empty -->
<div id="mainDialog" style="overflow: hidden">
  <div class="clearfix">
    <kb-multilang-selector
      v-if="multiLangs"
      :cultures="multiLangs.cultures"
      :default-culture="multiLangs.default"
    ></kb-multilang-selector>
  </div>
  <div class="container-fluid">
    <template v-for="($data,index) in contents">
      <div :key="index" v-if=" $data.show" class="form-group">
        <label class="control-label"
          >{{Kooboo.text.common.Content + '(' + $data.abbr + ')'}}</label
        >
        <div>
          <textarea
            v-kb-richeditor="richeditor($data.value)"
            v-model="$data.value"
            style="opacity: 0"
          ></textarea>
        </div>
      </div>
    </template>
  </div>
  <kb-media-dialog :data="mediaDialogData"></kb-media-dialog>
</div>

<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/kooboo-web-editor/richEditor.min.js",
      "/_Admin/Scripts/components/tinymceMonaco/plugin.min.js",
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/components/kbMultilangSelector.js",
      "/_Admin/Scripts/components/kb-media-dialog.js"
    ]);
    var self = new Vue({
      el: "#mainDialog",
      data: function() {
        return {
          mediaDialogData: null,
          contents: [],
          multiLangs: null,
          name: "",
          multiContents: [],
          blockId: Kooboo.getQueryString("nameOrId"),
          contentsValue: []
        };
      },
      mounted: function() {
        var self = this;

        if (!self.blockId) {
          window.info.show(Kooboo.text.info.versionLogParameterMissing, false);
        }

        Kooboo.EventBus.subscribe("ko/style/list/pickimage/show", function(
          ctx
        ) {
          Kooboo.Media.getList().then(function(res) {
            if (res.success) {
              res.model["show"] = true;
              res.model["context"] = ctx;
              res.model["onAdd"] = function(selected) {
                ctx.settings.file_browser_callback(
                  ctx.field_name,
                  selected.url + "?SiteId=" + Kooboo.getQueryString("SiteId"),
                  ctx.type,
                  ctx.win,
                  true
                );
              };
              self.mediaDialogData = res.model;
            }
          });
        });

        Kooboo.EventBus.subscribe("kb/multilang/change", function(target) {
          var content = _.findLast(self.contents, function(c) {
            return c.abbr == target.name;
          });

          if (content) {
            content.show = target.selected;
            self.adjustFrameHeight();
          }
        });

        $.when(
          Kooboo.HtmlBlock.Get({
            name: self.blockId
          }),
          Kooboo.Site.Langs()
        ).then(function(hbRes, langRes) {
          var r1 = hbRes[0],
            r2 = langRes[0];

          if (r1.success && r2.success) {
            self.name = r1.model.name;
            self.contentsValue = r1.model.values;
            self.multiLangs = r2.model;
            self.multiContents = r2.model;
            self.bindSaveHtmlBlockEvent();
          }
        });

        $(window).on("resize", function() {
          self.adjustFrameHeight();
        });
      },
      methods: {
        adjustFrameHeight: function() {
          setTimeout(function() {
            var height = window.document.body.clientHeight + 200;

            height = Math.min(parent.window.innerHeight - 200, height);

            window.parent.Kooboo.EventBus.publish(
              "kb/component/modal/set/height",
              { height: height }
            );
          }, 400);
        },
        bindSaveHtmlBlockEvent: function() {
          if (window.parent.__gl) {
            window.parent.__gl.saveHtmlblock = this.onSubmit;
          }
        },
        onSubmit: function() {
          var self = this;
          function submit() {
            var values = self.getMultiConents();
            Kooboo.HtmlBlock.syncPost({
              id: Kooboo.Guid.Empty,
              name: self.name,
              values: JSON.stringify(values)
            }).then(function(res) {
              if (
                window.parent.__gl &&
                window.parent.__gl.saveHtmlblockFinish
              ) {
                values &&
                  window.parent.__gl.saveHtmlblockFinish(
                    values[self.multiLangs.default]
                  );
              }
            });
          }

          submit();
        },
        getMultiConents: function() {
          var _values = {};
          _.forEach(self.contents, function(c) {
            _values[c.abbr] = c.value;
          });

          return _values;
        },
        richeditor: function(data) {
          var self = this;
          var item = {
            value: data,
            mediaDialogData: null,
            editorConfig: {
              min_height: 300,
              max_height: 600
            }
          };
          item = Vue.observable(item);
          this.$watch(
            function() {
              return item.mediaDialogData;
            },
            function(value) {
              self.mediaDialogData = value;
            }
          );

          return item;
        }
      },
      watch: {
        multiContents: function(multi) {
          var self = this;
          var _contentList = [];
          Object.keys(multi.cultures).forEach(function(abbr) {
            var value =
              typeof self.contentsValue == "object" &&
              self.contentsValue.hasOwnProperty(abbr)
                ? self.contentsValue[abbr]
                : "";

            if (!value) {
              if (
                typeof self.contentsValue == "object" &&
                self.contentsValue.hasOwnProperty("")
              ) {
                value = self.contentsValue[""];
              }
            }
            var _content = {
              show: multi.default == abbr,
              value: value,
              abbr: abbr
            };
            _contentList.push(_content);
          });

          self.contents = _contentList;
          self.adjustFrameHeight();
        }
      }
    });
  })();
</script>
